#!/usr/bin/env python3
"""
PinCaiCai 2.0 Environment Configuration Generator
Read database configuration from app/utils/database.py and generate .env file
Used for environment variable configuration during Docker deployment
"""

import os
import sys

# Add project root directory to Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app.utils.database import DB_CONFIG

def generate_env_file():
    """Generate .env file for Docker deployment"""
    env_content = f"""# PinCaiCai 2.0 Environment Configuration
# This file is automatically generated by generate_env.py
# Based on configuration in app/utils/database.py

# Database configuration (read from database.py)
DB_HOST={DB_CONFIG['host']}
DB_PORT={DB_CONFIG['port']}
DB_NAME={DB_CONFIG['database']}
DB_USER={DB_CONFIG['user']}
DB_PASSWORD={DB_CONFIG['password']}

# Flask configuration
FLASK_APP=main.py
FLASK_ENV=production
PYTHONPATH=/app

# Database connection URL (for internal Docker use)
DATABASE_URL=postgresql://{DB_CONFIG['user']}:{DB_CONFIG['password']}@host.docker.internal:{DB_CONFIG['port']}/{DB_CONFIG['database']}
"""
    
    with open('.env', 'w', encoding='utf-8') as f:
        f.write(env_content)
    
    print("🚀 PinCaiCai 2.0 Environment Configuration Generator")
    print("=" * 50)
    print("✅ Generated .env file")
    print("📋 Current database configuration:")
    print(f"   Host: {DB_CONFIG['host']}")
    print(f"   Port: {DB_CONFIG['port']}")
    print(f"   Database: {DB_CONFIG['database']}")
    print(f"   User: {DB_CONFIG['user']}")
    print(f"   Password: {'*' * len(DB_CONFIG['password'])}")
    print("=" * 50)
    print("💡 Tips:")
    print("   - To modify configuration, edit app/utils/database.py")
    print("   - Then re-run this script to generate new .env file")
    print("   - Use docker-compose up -d to start the application")

if __name__ == "__main__":
    try:
        generate_env_file()
    except Exception as e:
        print(f"❌ Failed to generate environment configuration: {e}")
        print("💡 Please ensure app/utils/database.py is properly configured")
        sys.exit(1)
